package cn.pzaily.orange.backup.controller;

import cn.pzaily.orange.backup.constants.BackupConstants;
import cn.pzaily.orange.backup.datasource.BackupDataSourceProperties;
import cn.pzaily.orange.backup.service.MysqlBackupService;
import cn.pzaily.orange.core.utils.FileUtils;
import cn.pzaily.orange.core.utils.http.AppHttpCodeEnum;
import cn.pzaily.orange.core.utils.http.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @PackageName: cn.pzaily.orange.backup.controller
 * @Description:
 * @Author: Pang
 * @Date: 2021-05-14 21:52
 */
@RestController
public class MysqlBackupController {

    @Autowired
    private MysqlBackupService mysqlBackupService;

    @Autowired
    private BackupDataSourceProperties properties;

    private String host;

    private String username;

    private String password;

    private String database;

    /**
     * 数据备份
     * @return
     */
    @RequestMapping(value = "/backup", method = RequestMethod.GET)
    public ResponseResult backup() {
        String backupFolderName = BackupConstants.DEFAULT_BACKUP_NAME + "_"
                + (new SimpleDateFormat(BackupConstants.DATE_FORMAT)).format(new Date());
        return backup(backupFolderName);
    }


    /**
     * 数据还原
     * @param name 还原的目录名称
     * @return
     */
    @RequestMapping(value = "/restore", method = RequestMethod.GET)
    public ResponseResult restore(@RequestParam(value = "name") String name) {

        getDatasource();
        String restoreFolderPath = BackupConstants.RESTORE_FOLDER + name;

        try {
            boolean restore = mysqlBackupService.restore(restoreFolderPath, host, username, password, database);
            if (!restore) {
                return ResponseResult.errorResult("还原失败");
            }
        } catch (Exception e) {
            return ResponseResult.errorResult(e.getMessage());
        }
        return ResponseResult.okResult("还原成功");
    }

    /**
     * 查询备份数据
     * @return
     */
    @RequestMapping(value = "/findRecords", method = RequestMethod.GET)
    public ResponseResult findBackupRecordList() {
        if (!new File(BackupConstants.DEFAULT_RESTORE_FILE).exists()) {
            backup(BackupConstants.DEFAULT_BACKUP_NAME);
        }

        List<Map<String, String>> records = new ArrayList<Map<String, String>>();
        File recordsFile = new File(BackupConstants.RESTORE_FOLDER);
        if (recordsFile.exists()) {
            for (File file : recordsFile.listFiles()) {
                Map<String, String> backup = new HashMap<>();
                backup.put("name", file.getName());
                backup.put("title", file.getName());
                if (BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(file.getName())) {
                    backup.put("title", "系统默认备份");
                }
                records.add(backup);
            }
        }

        records.sort(((o1, o2) ->
                BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(o1.get("name")) ? -1 :
                BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(o2.get("name")) ? 1 :
                o2.get("name").compareTo(o1.get("name"))));

        return ResponseResult.okResult(records);
    }

    /**
     * 删除指定的备份数据
     * @param name
     * @return
     */
    @RequestMapping(value = "/delete")
    public ResponseResult deleteBackupRecord(@RequestParam(value = "name") String name) {
        if (BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(name)) {
            return ResponseResult.errorResult("系统默认备份无法删除");
        }
        String restoreFilePath = BackupConstants.BACKUP_FOLDER + name;
        try {
            FileUtils.deleteFile(new File(restoreFilePath));
        } catch (Exception e) {
            return ResponseResult.errorResult(e.getMessage());
        }
        return ResponseResult.okResult();
    }

    /**
     * 获取数据源
     */
    private void getDatasource() {
        this.host = properties.getHost();
        this.username = properties.getUsername();
        this.password = properties.getPassword();
        this.database = properties.getDatabase();
    }

    private ResponseResult backup(String backupFolderName) {
        getDatasource();
        String backupFolderPath = BackupConstants.BACKUP_FOLDER + backupFolderName + File.separator;
        String fileName = BackupConstants.BACKUP_FILE_NAME;

        try {
            boolean success = mysqlBackupService.backup(host, username, password, backupFolderPath, fileName, database);
            if (!success){
                return ResponseResult.okResult("备份失败");
            }
        } catch (Exception e) {
            return ResponseResult.okResult(e.getMessage());
        }
        return ResponseResult.okResult("备份成功");
    }
}
